package Q5;

import java.io.*;
import java.net.Socket;

public class ServerTool {

    //创建用户的目录
    public static void creatLocalStorage() {
        File file = new File("D:/Talk/server/");
        if (file.exists()) {
            System.out.println("用户存储目录已存在");
        } else {
            System.out.println("目录创建成功" + file.getPath());
        }
    }

    //发送文件
    public static void sendFileToClient(int id,File file, String name) {
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(new FileOutputStream("D:/Talk/server"));

            byte[] arr = new byte[2048];
            int res = 0;
            while((res = bis.read(arr)) > 0) {
                bos.write(arr, 0, res);
                bos.flush();
                if(res < 2048) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void shareMsg (int id, String name, String msg) {
        PrintStream ps = null;
        msg = name + ": " + msg;
        System.out.println(msg);
        //遍历服务器连接对象并群发信息
        for (int i = 0; i < TalkServer.socketNum; i++) {
            if (i == id) {
                continue;
            }
            Socket s = TalkServer.sockets[i];
            if (!s.isClosed()) {
                try {
                    ps = new PrintStream(s.getOutputStream());
                    ps.println(msg);
                } catch (IOException e) {
                    System.out.println("发送失败");
                }
            }
        }
    }

    public static void receiveFile(int id, String fileName, String name){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //初始化输入输出流
            bos = new BufferedOutputStream(new FileOutputStream("D:/Talk/server/"+fileName));
            bis = new BufferedInputStream(TalkServer.sockets[id].getInputStream());
            byte[] arr = new byte[2048];
            int res = 0;
            while((res = bis.read(arr)) > 0) {
                bos.write(arr, 0, res);
                bos.flush();
                if(res < 2048) {
                    break;
                }
            }
            System.out.println("文件已保存");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
